package com.clustertech.crawler.controller;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.clustertech.crawler.domain.NewsFeed;
import com.clustertech.crawler.json.JSONArray;
import com.clustertech.crawler.json.JSONObject;
import com.clustertech.crawler.service.ClusterService;
import com.clustertech.crawler.utils.SinaNewsExtractor;

public class CrawlController extends AbstractController {
	
	private ClusterService service;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		List<NewsFeed> newsFeeds = service.crawl();
		response.setContentType("text/json");
		response.setCharacterEncoding(SinaNewsExtractor.ENCODING);
    	PrintWriter output = new PrintWriter(response.getOutputStream());
    	JSONArray jarr = new JSONArray();
    	JSONObject jobj = null;
    	for (int i = 0; i < newsFeeds.size(); i++) {
    		NewsFeed newsFeed = newsFeeds.get(i);
    		jobj = new JSONObject();
    		jobj.put("title", newsFeed.getTitle());
    		jobj.put("timestamp", newsFeed.getTimeStamp());
    		jobj.put("body", newsFeed.getBody());
    		jarr.put(jobj);
    	}
    	output.println(jarr.toString());
    	output.flush();
		return null;
	}

	public ClusterService getService() {
		return service;
	}

	public void setService(ClusterService service) {
		this.service = service;
	}

}
